#!/usr/bin/env node

import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * Index statistics utility - Shows indexing performance and statistics
 */

console.log('📊 MCP Java Decompiler - Index Statistics');
console.log('=' + '='.repeat(50));

// MCP request to get a sample class search which will show index stats
const mcpRequest = {
    jsonrpc: "2.0",
    id: 1,
    method: "tools/call",
    params: {
        name: "find_class_in_local_repository",
        arguments: {
            className: "ExpandDomain" // Use a known class to trigger index loading
        }
    }
};

// Start MCP server process
const serverProcess = spawn('node', ['dist/index.js'], {
    cwd: __dirname,
    stdio: ['pipe', 'pipe', 'inherit']
});

let output = '';
let hasReceived = false;

// Process server output
serverProcess.stdout.on('data', (data) => {
    const chunk = data.toString();
    output += chunk;
    
    // Check for complete JSON response
    try {
        const lines = output.split('\n').filter(line => line.trim());
        for (const line of lines) {
            if (line.startsWith('{') && !hasReceived) {
                const response = JSON.parse(line);
                if (response.result && response.result.content) {
                    hasReceived = true;
                    handleResponse(response);
                    serverProcess.kill();
                    return;
                }
            }
        }
    } catch (e) {
        // Continue waiting for more data
    }
});

// Send request to server
serverProcess.stdin.write(JSON.stringify(mcpRequest) + '\n');

// Set timeout
const timeout = setTimeout(() => {
    console.log('❌ Request timeout (30 seconds)');
    serverProcess.kill();
    process.exit(1);
}, 30000);

// Handle response
function handleResponse(response) {
    clearTimeout(timeout);
    
    try {
        const result = JSON.parse(response.result.content[0].text);
        
        console.log(`🏗️  Repository Indexing Status:`);
        console.log(`   📁 Repository Path: ${result.repositoryPath}`);
        console.log(`   ✅ Index Ready: ${result.indexReady ? '是' : '否'}`);
        console.log('');
        
        if (result.indexReady) {
            console.log(`📈 Index Statistics:`);
            console.log(`   🗂️  Total Artifacts Indexed: ${result.totalArtifactsScanned}`);
            console.log(`   🏷️  Total Classes Indexed: ${result.totalClassesIndexed}`);
            console.log(`   🔍 Search Results: ${result.matchesFound} matches for "${result.className}"`);
            console.log('');
            
            // Calculate index efficiency metrics
            if (result.classes && result.classes.length > 0) {
                console.log(`🎯 Search Performance:`);
                console.log(`   ⚡ Index-based search: ENABLED`);
                console.log(`   📝 Sample class found: ${result.classes[0].fullName}`);
                console.log(`   📦 In artifact: ${result.classes[0].artifact.groupId}:${result.classes[0].artifact.artifactId}:${result.classes[0].artifact.version}`);
                console.log(`   ✅ Decompilation: ${result.classes[0].decompiled ? '成功' : '失败'}`);
            }
        } else {
            console.log(`❌ Index not ready - performance will be degraded`);
            console.log(`💡 Index will be generated on first use automatically`);
        }
        
    } catch (error) {
        console.log('❌ Failed to parse response:', error.message);
        console.log('Raw response:', response.result.content[0].text);
    }
}

// Handle process errors
serverProcess.on('error', (error) => {
    clearTimeout(timeout);
    console.log('❌ Failed to start MCP server:', error.message);
    console.log('💡 Please run: npm run build');
});

serverProcess.on('exit', (code) => {
    if (code !== 0 && !hasReceived) {
        console.log(`❌ MCP server exited abnormally with code: ${code}`);
    }
});